import { defineStore } from 'pinia';
import { getUserProfile, miniProgramLogin, checkUserRegistration, type UserProfile } from '@/api/user';

// 用户状态接口
interface UserState {
  token: string;
  userInfo: UserProfile | null;
  isLoggedIn: boolean;
}

/**
 * 用户状态存储
 */
export const useUserStore = defineStore('user', {
  // 状态
  state: (): UserState => {
    try {
      const token = uni.getStorageSync('token') || ''
      const userInfoStr = uni.getStorageSync('userInfo')
      const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null

      return {
        token,
        userInfo,
        isLoggedIn: !!token,
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
      return {
        token: '',
        userInfo: null,
        isLoggedIn: false,
      }
    }
  },

  // 计算属性
  getters: {
    /**
     * 是否已登录
     */
    isAuthenticated: (state): boolean => !!state.token && !!state.userInfo,
  },

  // 方法
  actions: {
    /**
     * 设置token
     * @param token 用户令牌
     */
    setToken(token: string): void {
      this.token = token;
      uni.setStorageSync('token', token);
    },

    /**
     * 设置用户信息
     * @param userInfo 用户信息
     */
    setUserInfo(userInfo: UserProfile | null): void {
      this.userInfo = userInfo;
      this.isLoggedIn = !!userInfo;
      if (userInfo) {
        uni.setStorageSync('userInfo', JSON.stringify(userInfo));
      } else {
        uni.removeStorageSync('userInfo');
      }
    },

    /**
     * 登出
     */
    logout(): void {
      this.token = '';
      this.userInfo = null;
      this.isLoggedIn = false;
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
    },

    /**
     * 检查用户是否已注册
     */
    async checkUserRegistration(code: string): Promise<{ isRegistered: boolean; user?: UserProfile }> {
      try {
        const response = await checkUserRegistration({ code });
        if (response.code === 200) {
          return {
            isRegistered: response.data.isRegistered,
            user: response.data.user
          };
        }
        return { isRegistered: false };
      } catch (error) {
        console.error('检查用户注册状态失败:', error);
        return { isRegistered: false };
      }
    },

    /**
     * 微信小程序登录
     * @param loginData 登录数据
     */
    async loginWithWechat(loginData: {
      code: string;
      redirectUri: string;
      nickname: string;
      avatarUrl: string;
    }): Promise<void> {
      try {
        console.log('loginData', loginData)
        const response = await miniProgramLogin(loginData);

        if (response.code === 200) {
          // 设置token
          this.setToken(response.data.token);

          // 设置用户信息
          this.setUserInfo(response.data.user);

          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
        } else {
          throw new Error(response.message || '登录失败');
        }
      } catch (error) {
        console.error('微信登录失败:', error);
        throw error;
      }
    },

    /**
     * 获取用户信息
     */
    async fetchUserProfile(): Promise<void> {
      try {
        const response = await getUserProfile();
        if (response.code === 200) {
          this.setUserInfo(response.data);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 如果获取用户信息失败，清除登录状态
        this.logout();
        throw error;
      }
    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus(): Promise<boolean> {
      try {
        if (!this.token) {
          return false;
        }

        // 验证token是否有效
        await this.fetchUserProfile();
        return true;
      } catch (error) {
        console.error('检查登录状态失败:', error);
        // token无效，清除登录状态
        this.logout();
        return false;
      }
    },
  },

  // 持久化
  persist: true,
});

// 导出用户信息接口，供其他模块使用
export type { UserProfile };